/**
 * Copyright 2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edi.runtime.component
{
	import com.edi.proxy.component.HttpProxy;
	import com.edi.proxy.component.HttpProxyResult;
	import com.edi.proxy.component.PO;
	import com.edi.proxy.component.POParam;
	import com.edi.proxy.component.TPOParam;
	import com.edi.runtime.Event.EDIDataEvent;
	import com.edi.runtime.Event.EDIEventProxy;
	
	import mx.binding.utils.ChangeWatcher;
	import mx.collections.ArrayCollection;
	import mx.collections.XMLListCollection;
	import mx.events.CollectionEvent;
	import mx.messaging.messages.ErrorMessage;

	/**
	 * 继承自 XMLListCollection 对象，实现数据表的操作
	 * 
	 */
	public class EDIDataTable extends XMLListCollection
	{
		private var _cursorIndex:int=-1;
		private var _dataSourceName:String="";
		private var _removeIndex:int;   
		private var _addIndex:int;
		private var dataLoadList:Array;
		private var dataRollingList:Array;
		
		private var rowStateList:ArrayCollection;
		/**
		 * 字段集合 
		 */		
		public var fieldList:Array;
		
		private var delRowList:Array;
		
		private var _autoCommit:Boolean;
		private var ediDs:EDIDataSource;
		
		private var selfEdt:EDIDataTable;
		
		private static const NONE:String="NONE";
		
		private var shadowSource:XML;
		
		private var _dataTree:EDIDataTree;
		/**
		 *  数据滚动之后出发的回调函数 
		 */		
		public var onDataRollingAfter:Function;
		
		/**
		 * 数据提交之后出发的回调函数 
		 */		
		public var onDataUpdateAfter:Function;
		
		/**
		 * 插入数据时所引发的回调
		 */		
		public var onDataInsert:Function;
		
		/**
		 *删除数据时所引发的回调 
		 */		
		public var onDataDelete:Function;
		
		/**
		 * 地址 
		 */		
		public var url:String;
		
		/**
		 * 新行状态 
		 */		
		public var newRowState:String="";
		
		/**
		 * 参数集合 
		 */		
		public var poparm:Array;
		
		/**
		 * 事务名称 
		 */		
		public var transaction:String="";
		
		/**
		 * 构造  Table对象 
		 * @param source 数据源,即表
		 * @param ediDs 所属的DataSource
		 * 
		 */		
		
		public function EDIDataTable(source:XMLList=null,ediDs:EDIDataSource=null)
		{
			super(source);
			
			selfEdt=this;
			dataLoadList=new Array();
			dataRollingList=new Array();
			rowStateList=new ArrayCollection();
			fieldList= new Array();
			delRowList= new Array();
			
			poparm=new Array();
			
			this.ediDs = ediDs;
			
			if(source!=null)
			{
				loadSource(source);
			}	
			//查找完毕 
			addEventListener(CollectionEvent.COLLECTION_CHANGE,xmlCollectionChange);
		}
		
		/**
		 * 添加poparam对象 
		 * @param value
		 * 
		 */		
		public function addPoparm(value:POParam):void
		{
			if(value!=null)
			{
				poparm.push(value);
			}
		}
		
		/**
		 * 加载新数据集
		 * @param source
		 * 
		 */		
		public function loadNewSource(source:XMLList):void
		{
			
			rowStateList.removeAll();
			fieldList.splice(0,fieldList.length);
			delRowList.splice(0,delRowList.length);
			
			dataLoadList.splice(0,dataLoadList.length);
			//dataRollingList.splice(0,dataRollingList.length);
			
			
			
			loadSource(source);
			this.source=source;
			dataSourceName=_dataSourceName;
		}
		
		/**
		 * 加载数据源 
		 * @param source
		 * 
		 */		
		private function loadSource(source:XMLList):void
		{
			shadowSource=new XML(<db>{source.copy()}</db>);
			
			var i:int;
			var iCount:int=source.length();
			var obj:Object;
			
			for(i=0;i<iCount;i++)
			{
				obj=new Object();
				obj["state"]=newRowState!=""?"add":NONE;
				rowStateList.addItem(obj);
			}
				
			//获得返回过来的字段
			if(source.length()>0)
			{
				var xmlList:XMLList=source[0].children();
				iCount=xmlList.length();
				for(i=0;i<iCount;i++)
				{
					obj=new Object();
					obj["field"]=(xmlList[i] as XML).localName();
					obj["fieldType"]=xmlList[i]["@fieldType"].toString();
					obj["primaryKey"]=xmlList[i]["@primaryKey"].toString();
					fieldList.push(obj);
				}
			}
		}
		
		/**
		 * 释放该对象 
		 * 
		 */		
		public function destroy():void
		{
			this.removeEventListener(CollectionEvent.COLLECTION_CHANGE,xmlCollectionChange);
			onDataRollingAfter=null;
			onDataUpdateAfter=null;
			onDataInsert=null;
			onDataDelete=null;
		}
		
		/**
		 * 设置数据源名称 
		 * @param value 数据源名称
		 * 
		 */		
		public function set dataSourceName(value:String):void
		{
			var i:int;
			var obj:Object;
			var j:int;
			if(_dataSourceName=="")
			{ 
				for(i=0;i<EDIEventProxy.dataRollingList.length;i++)
				{
					if(EDIEventProxy.dataRollingList[i]["tableName"].toString().toLowerCase()==value.toLowerCase())
					{
						if(EDIEventProxy.dataRollingList[i]["edi"] is IEDIComponent)
						{
							var edi:IEDIComponent=EDIEventProxy.dataRollingList[i]["edi"] as IEDIComponent;
							
						
							if(edi is EDITextInput || edi is EDITextArea || edi is EDIDateField || edi is EDIBasicData)
							{
								bindProperty(this,edi.field,edi,"text");
							}
							else if( edi is EDIBasicData)
							{
								bindProperty(this,edi.field,edi,"saveValue");
							}
							else if(edi is EDICheckBox )
							{
								bindProperty(this,edi.field,edi,"selected");
							}
							else if(edi is EDIList || edi is EDIComboBox)
							{
								bindProperty(this,edi.field,edi,"selectedIndex");
							}
							else if (edi is EDIRadioButtonGroup)
							{
								bindProperty(this,edi.field,edi,"selectItemValue");
							}
							else if(edi is EDIImage)
							{
								bindProperty(this,edi.field,edi,"source");
							}
							
							dataRollingList.push(EDIEventProxy.dataRollingList[i]);
						}
					}
				}
			}
			_dataSourceName=value;
			
			for(i=0;i<EDIEventProxy.dataLoadList.length;i++)
			{
				if(EDIEventProxy.dataLoadList[i]["edi"] is IEDIDataLoad && EDIEventProxy.dataLoadList[i]["tableName"]==value)
				{
					var ede:EDIDataEvent=new EDIDataEvent(EDIDataEvent.Data_Load); 
					ede.value=this;
					ede.ediTarget=this;
					ede.index=cursorIndex;
					ede.tableName=dataSourceName;
					(EDIEventProxy.dataLoadList[i]["edi"] as IEDIDataLoad).dataLoadHandler(ede);
					dataLoadList.push(EDIEventProxy.dataLoadList[i]);
				}
			}
			//this.cursorIndex=0;
		}
		
		/**
		 * 添加字段 
		 * @param fieldName 字段名
		 * @param fieldType 字段类型
		 * @param primaryKey 是否是主键
		 * 
		 */		
		public function addField(fieldName:String,fieldType:String,primaryKey:Boolean=false):void
		{
			var i:int;
			fieldName=fieldName.toLowerCase();
			for(i=0;i<fieldList.length;i++)
			{
				if(fieldList[i]["field"]==fieldName)
				{
					fieldList[i]["fieldType"]=fieldType;
					fieldList[i]["primaryKey"]=primaryKey == true ? "1":"";
//					mx.controls.Alert.show(fieldList[i]["primaryKey"] as String);
					break;
				}
			}
			
			if(i==fieldList.length)
			{
				var obj:Object=new Object();
				obj["field"]=fieldName
				obj["fieldType"]=fieldType;
				obj["primaryKey"]=primaryKey == true ? "1":"";
//				mx.controls.Alert.show(obj["primaryKey"] as String);
				fieldList.push(obj);
			}
		}
		
		private function bindProperty(dataTable:EDIDataTable,prop:String,
                                host:Object, chain:Object,
                                commitOnly:Boolean = false):void
	    {
	        var w:ChangeWatcher =
	            ChangeWatcher.watch(host, chain, null, commitOnly);
	        if (w != null)
	        {
	            var assign:Function = function(event:*):void
	            {
	            	if(dataTable.cursorIndex!=-1)
	            	{
	            		if(host is IEDIComponent)
	            		{
	            			if(host is EDIImage)
	            			{
	            				var strPath:String=(host as IEDIComponent).ediValue;
	            				if(strPath.indexOf("[")!=-1)
	            				{
	            					return ;
	            				}
	            			}
	            			if(dataTable.selectRow[prop] != (host as IEDIComponent).ediValue)
	            			{
	            				dataTable.selectRow[prop] = (host as IEDIComponent).ediValue;
	            			}
	            		}
	            		else
	            		{
	            			if(dataTable.selectRow[prop] != w.getValue())
	            			{
	                			dataTable.selectRow[prop] = w.getValue();
	               			}
	              		}
	              		
	             	}
	            };
	            w.setHandler(assign);
	            assign(null);
	        }
	    }
		
		public function get dataSourceName():String
		{
			return _dataSourceName;
		}
		
		/**
		 * 是否自动提交 
		 * @param value
		 * 
		 */		
		public function set autoCommit(value:Boolean):void
		{
			_autoCommit=value;
		}
		public function get autoCommit():Boolean
		{
			return _autoCommit;
		}
		
		/**
		 * 设置指定的行或获得当前行  
		 * @param value
		 * 
		 */		
		public function set cursorIndex(value:int):void
		{
			if(_cursorIndex!=-1)
			{
//				EDIApplication.outputDebug("进入EDIDataTable-->set cursorIndex: ");
//				EDIApplication.outputDebug("进入EDIDataTable-->_cursorIndex: "+_cursorIndex);
				//本行数据发生变化
				var oldIndex:int=_cursorIndex;
				if(_cursorIndex<length && rowStateList[_cursorIndex]["state"].toString()=="update")
				{
					if(autoCommit && ediDs!=null)
					{
						var por:TPOParam=new TPOParam();
						por.cmdXml=rowToXML(_cursorIndex,this.source);
						por.methods=PO.UPDATE;
						proxySend(por,null,null,
							function(event:HttpProxyResult):void
							{
								var tempX:XMLList=(selfEdt[oldIndex] as XML).children();
								var iCount:int=tempX.length();
								var field:String;
								rowStateList[oldIndex]["state"]=NONE;
								for(var i:int=0;i<iCount;i++)
								{
									field=(tempX[i] as XML).localName().toString();
									shadowSource.children()[oldIndex][field]=selfEdt[oldIndex][field].toString();
								}
							}
							,
							function(event:HttpProxyResult):void
							{
								var tempX:XMLList=(selfEdt[oldIndex] as XML).children();
								var iCount:int=tempX.length();
								var field:String;
								rowStateList[oldIndex]["state"]=NONE;
								for(var i:int=0;i<iCount;i++)
								{
									field=(tempX[i] as XML).localName().toString();
									selfEdt.source[oldIndex][field]=shadowSource.children()[oldIndex][field].toString();
								}
								rowStateList[value]["state"]=NONE;
							}
						);
					}
				}
			}
//			EDIApplication.outputDebug("进入EDIDataTable-->value: "+value);
			_cursorIndex=value;
			if(_cursorIndex>-1 && _cursorIndex<length)
			{
				var i:int;
				var ede:EDIDataEvent
				for(i=0;i<dataRollingList.length;i++)
				{
					ede=new EDIDataEvent(EDIDataEvent.Data_RollingAfter); 
					ede.value=this[_cursorIndex];
					ede.ediTarget=this;
//					EDIApplication.outputDebug("EDIDataTable-->edeindex: "+ede.index);
//					EDIApplication.outputDebug("EDIDataTable-->_cursorIndex: "+_cursorIndex);
					ede.index=_cursorIndex;
					ede.tableName=dataSourceName;
					(dataRollingList[i]["edi"] as IEDIComponent).dataRollingHandler(ede);
				}
				
				//触发外部事件
				if(onDataRollingAfter!=null)
				{
					ede=new EDIDataEvent(EDIDataEvent.Data_RollingAfter); 
					ede.value=this[_cursorIndex];
					ede.ediTarget=this;
					ede.index=_cursorIndex;
					ede.tableName=dataSourceName;
					onDataRollingAfter(ede);
				}
			}
		}
		public function get cursorIndex():int
		{
			return _cursorIndex;
		}
		
		public function get selectRow():XML
		{
			return cursorIndex!=-1?this[cursorIndex]:null;
		}
		
		private function rowAddProperty(value:XML):XML
		{
			var row:XML=new XML(<row />);
			var i:int;
			var str:String;
			for(i=0;i<fieldList.length;i++)
			{
				if(value.hasOwnProperty(fieldList[i]["field"]))
				{
					str="<"+fieldList[i]["field"]+" fieldType=\""+fieldList[i]["fieldType"]+"\" "+(fieldList[i]["primaryKey"]!=""?" primaryKey=\"1\"":"")+"><![CDATA["+value[fieldList[i]["field"]]+"]]></"+fieldList[i]["field"]+">";
					row.appendChild(str);
				}
			}
			return row;
		}
		
		/**
		 * 获得该行的xml信息
		 * @param index 行为之
		 * @param table 表名称
		 * @return 
		 * 
		 */		
		public function rowToXML(index:int=-1,table:Object=null):XML
		{
			if(table==null){table=this.source;}
			var db:XML=new XML(<table name={this.dataSourceName}/>);
			if(index==-1){index=cursorIndex}
			if(index==-1){index=0}
			db.appendChild(rowAddProperty(table[index]));
			return db;
		}
		
		/**
		 * 生成xml协议串
		 * @return 
		 * 
		 */		
		public function toXML():XML
		{
			var db:XML=new XML(<table name={this.dataSourceName}/>);
			var xmlList:XML;
			var i:int;
			var ret:Boolean=false;
			for(i=0;i<rowStateList.length;i++)
			{
				if(rowStateList[i]["state"].toString()!=NONE)
				{
					xmlList=rowAddProperty(this[i]);
					xmlList.@Operation=rowStateList[i]["state"].toString();
					db.appendChild(xmlList);
					ret=true;
				}
			}
			for(i=0;i<delRowList.length;i++)
			{
				xmlList=rowAddProperty(delRowList[i]);
				xmlList.@Operation="remove";
				db.appendChild(xmlList);
				ret=true;
			}	
			return ret?db:null;
		}
		
		/**
		 *  清空该表 
		 * 
		 */		
		override public function removeAll():void
		{
			var i:int;
			
			var delSource:XMLList=source.copy();
			
			if(autoCommit && ediDs!=null)
			{
				var db:XML=new XML(<table name={this.dataSourceName}/>);
				var xmlList:XML;
				for(i=0;i<rowStateList.length;i++)
				{
					xmlList=rowAddProperty(this[i]);
					xmlList.@Operation="remove";
					db.appendChild(xmlList);
				}
				for(i=0;i<delRowList.length;i++)
				{
					xmlList=rowAddProperty(delRowList[i]);
					xmlList.@Operation="remove";
					db.appendChild(xmlList);
				}
				
				var por:TPOParam=new TPOParam();
				por.cmdXml=db;
				por.methods=PO.DELETE;
				proxySend(por,null,null,function(event:HttpProxyResult):void
					{
					    var len:int = selfEdt.length;
					    var i:int;
				        if (len > 0)
				        {
				          if (selfEdt.localIndex)
				          {
				             for (i = len - 1; i >= 0; i--)
				             {
				                selfEdt.list.removeItemAt(i);
				             }
				          }
				          else
				          {
				             selfEdt.list.removeAll();
				          }
				          
				          var xmlList:XMLList=shadowSource.children();
				          for (i = len - 1; i >= 0; i--)
				          {
				          	delete xmlList[i];
				          }
				          
				          delRowList.splice(0,delRowList.length);
				          rowStateList.removeAll();
				       }
					} 
				);
			}
			else  //若未提交服务器 则作删除记录
			{
				for(i=0;i<length;i++)
				{
					if(rowStateList[i]["state"]!="add")
					{
						delRowList.push(this[i]);
					} 
				} 
				rowStateList.removeAll();
				super.removeAll();
			}
			
			if(onDataDelete!=null)
			{
				var ede:EDIDataEvent=new EDIDataEvent(EDIDataEvent.Data_Delete); 
				ede.value=delSource;
				ede.ediTarget=this;
				ede.index=-1;
				ede.tableName=dataSourceName;
				onDataDelete(ede);
			}
						
		}
		
		/**
		 * 删除当前行 
		 * @return 
		 * 
		 */		
		public function removeCurrentRow():Object 
		{
			return removeItemAt(cursorIndex);
		}
		

		/**
		 * 删除指定行 
		 * @param index 要删除的行号
		 * @return 
		 * 
		 */		
		override public function removeItemAt(index:int):Object
		{
			if(index==-1){index=(cursorIndex==-1)?this.length:cursorIndex;}
			else if(index>this.length){index=this.length}
			var retObj:Object;
			var delObj:Object=source[index]
			
			if(autoCommit && ediDs!=null)
			{
				var por:TPOParam=new TPOParam();
				por.cmdXml=rowToXML(0,this[index]);
				por.methods=PO.DELETE;
				
				proxySend(por,null,null,
					function(event:HttpProxyResult):void
					{
					    retObj=selfEdt.list.removeItemAt(index);  //执行删除
					    rowStateList.removeItemAt(index);  //清楚状态
					    delete shadowSource.children()[index];
					}
				);
				
			}
			else //若未提交服务器 则作删除记录
			{
				_removeIndex=index;
				if(rowStateList[index]["state"]!="add")
				{
					delRowList.push(this[index]);
				}
				retObj=super.removeItemAt(index);
			} 
			
			if(onDataDelete!=null)
			{
				var ede:EDIDataEvent=new EDIDataEvent(EDIDataEvent.Data_Delete); 
					ede.value=delObj;
					ede.ediTarget=this;
					ede.index=index;
					ede.tableName=dataSourceName;
					onDataDelete(ede);
			}
			
			cursorIndex=0;
			
			return retObj;
		}
		
		/**
		 * 添加行到指定位置 
		 * @param item 要添加的行信息
		 * @param index 添加到得位置
		 * 
		 */		
		override public function addItemAt(item:Object, index:int):void
		{			
			if(index==-1){index=(cursorIndex==-1)?this.length:cursorIndex;}
			else if(index>this.length){index=this.length} 
			_addIndex=index;
			
			if(autoCommit && ediDs!=null)
			{
				var por:TPOParam=new TPOParam();
				por.cmdXml=rowToXML(0,item);
				por.methods=PO.INSERT;
				proxySend(por,null,null,
					function(event:HttpProxyResult):void
					{
						selfEdt.list.addItemAt(item,_addIndex);	
						shadowSource.appendChild((item as XML).copy());	
					}
				);
			}
			else
			{
				super.addItemAt(item,_addIndex);
			}
			
			if(onDataInsert!=null)
			{
				var ede:EDIDataEvent=new EDIDataEvent(EDIDataEvent.Data_Insert); 
					ede.value=item;
					ede.ediTarget=this;
					ede.index=length;
					ede.tableName=dataSourceName;
					onDataInsert(ede);
			}
		}
		
		/**
		 * commitToServer 提交至服务器
		 * 
		 * listenerResult：提交成功后的方法
		 * listenerFault：提交失败后的方法
		 * obj： 回调时需要用的对象
		 * successMessage: 提交成功信息
		 * failedMessage： 提交失败信息
		 * 
		 * @return
		 */
		public function commitToServer(listenerResult:Function=null,listenerFault:Function=null,obj:Object=null,successMessage:String=null,failedMessage:String=null):void 
		{
			var por:TPOParam=getTPOParam();
			if(por != null)
			{
				proxySend(por,successMessage,failedMessage,function(event:HttpProxyResult):void{
					for(var i:int=0;i<rowStateList.length;i++)
					{
						rowStateList[i]["state"]=EDIDataTable.NONE;
					}
					delRowList.splice(0,delRowList.length);
					if (listenerResult!=null)
						listenerResult(event,obj);
				},listenerFault);
			}
		}
		
		/**
		 * 生成tpoparam对象 
		 * @return 
		 * 
		 */		
		public function getTPOParam():TPOParam
		{
			var por:TPOParam=null;
			var cmdX:XML=toXML();
			if(cmdX!=null)
			{
				por=new TPOParam();
				por.cmdXml=cmdX
				por.transaction=transaction;		
				por.methods=PO.UPDATE;
			}
			return por;
		}
		

		private function proxySend(value:TPOParam,successMessage:String,failedMessage:String,listenerResult:Function=null,listenerFault:Function=null):void
		{
			var proxy:HttpProxy=new HttpProxy(EDIApplication.appName,false);
			proxy.addPoParam(value);
			for(var i:int=0;i<poparm.length;i++)
			{
				proxy.addPoParam((poparm[i] as POParam));
			}
			proxy.url=this.url;
			proxy.successMessage = successMessage;
			proxy.failedMessage = failedMessage;
			proxy.resultCallback=listenerResult;
			proxy.faultCallBack=listenerFault;
			proxy.send();
		}
		
		/**
		 * 将二维表格转换成树状结构 
		 * @param idField 编号
		 * @param pidField 父编号
		 * @param rootValue 根节点值
		 * @param labelField 显示字段名
		 * @param orderByField 排序字段
		 * @param desc 排序方式
		 * @return  类型EDIDataTree 
		 * 
		 */		
		public function toTree(idField:String="",pidField:String="",rootValue:String="",labelField:String="",orderByField:String="",desc:Boolean=false):EDIDataTree
		{
			_dataTree=new EDIDataTree(this,idField,pidField,rootValue,labelField,orderByField,desc)
			return _dataTree;
		}
		
		public function get tree():EDIDataTree
		{
			return _dataTree;
		}
		
		/**
		 *  获得指定行
		 * @param index 指定的行索引
		 * @return EDIDataRow类型
		 * 
		 */		
		public function getRow(index:int):EDIDataRow
		{
			var obj:Object;
			var fl:Array=new Array();
			for(var i:int=0;i<fieldList.length;i++)
			{
				obj=new Object();
				obj["field"]=fieldList[i]["field"];
				obj["fieldType"]=fieldList[i]["fieldType"];
				obj["primaryKey"]=fieldList[i]["primaryKey"];
				obj["value"]=this[index][fieldList[i]["field"]].toString();
				fl.push(obj);
			}
			return new EDIDataRow(fl,this);
		}
		
//		public function upDataRow(row:EDIDataRow,index:int):void
//		{
//			var obj:Object=row.getFieldValue();
//			for(var i:int=0;i<fieldList.length;i++)
//			{
//				this[index][fieldList[i]["field"]]=obj[fieldList[i]["field"]].toString();
//			}
//		}
		
		/**
		 * 生成一个新航 
		 * @return 
		 * 
		 */		
		public function newRow():EDIDataRow
		{
			return new EDIDataRow(fieldList,this);
		}
		
		/**
		 * 删除所有字段 
		 * 
		 */		
		public function removeAllField():void
		{
			fieldList.splice(0,fieldList.length);
		}		
		
		/**
		 * 添加一个新行 
		 * @param value EDIDataRow类型，新添加的行
		 * @return  是否添加成功
		 * 
		 */		
		public function addRow(value:EDIDataRow):Boolean
		{
			var ret:Boolean=false;
			try
			{	
				if(this.newRowState!="")
				{
					super.removeItemAt(0);
					this.newRowState="";
				}			
				this.addItem(value.toRow());
				ret=true;
			}
			catch(e:ErrorMessage)
			{
				
			}
			return ret;
		}
		
		/**
		 * 删除指定行 
		 * @param index 要删除行的索引
		 * @return 
		 * 
		 */		
		public function delRow(index:int):Boolean
		{
			var ret:Boolean=false;
			this.removeItemAt(index);
			return ret;
		}
		
		/**
		 * 更新行信息 
		 * @param value 要更新的行
		 * @param index 被更新行的索引
		 * @return 
		 * 
		 */		
		public function upDataRow(value:EDIDataRow,index:int=-1):Boolean
		{
			if(index==-1)
			{
				addRow(value);
			}
			else
			{
				var ci:int=cursorIndex;
				cursorIndex=index;
				var obj:Object;
				var field:String;
				var fieldValue:String;
				for(var i:int=0;i<value.rowFiled.length;i++)
				{
					obj=value.rowFiled[i];
					field=obj["field"];
					fieldValue=obj["value"];
					if(this[index].hasOwnProperty(field))
					{
						this[index][field]=fieldValue;
					}
				}
				cursorIndex=ci;
			}
			return true;
		}
		
		protected function xmlCollectionChange(event:CollectionEvent):void
		{
			switch(event.kind)
			{
				case "add":
				{
					var obj:Object=new Object();
					obj["state"]=(autoCommit && ediDs!=null)?NONE:event.kind;
					rowStateList.addItemAt(obj,_addIndex);
					break;
				}
				case "remove":
				{
					if(event.items.length==1 && !(autoCommit && ediDs!=null))
					{
						rowStateList.removeItemAt(_removeIndex);
					}
					break;
				}
				case "update":
				{
					if(rowStateList[cursorIndex]["state"]!="add")
					{
						rowStateList[cursorIndex]["state"]=event.kind;
					}
					if(_dataTree!=null)
					{
						_dataTree.updateTreeNodeForRow(this[cursorIndex]);
					}
					if(onDataUpdateAfter!=null)
					{
						var ede:EDIDataEvent=new EDIDataEvent(EDIDataEvent.Data_UpdateAfter); 
							ede.value=source[cursorIndex];
							ede.ediTarget=this;
							ede.index=cursorIndex;
							ede.tableName=dataSourceName;
							onDataUpdateAfter(ede);
					}
					break;
				}
			}
		}
		
	}
}